package com.app.serial.threads;/**
 * @program: app-admin
 * @name CheckSerialThread
 * @description: 监测串口的线程
 */

import com.app.serial.config.SerialConfig;
import com.app.serial.jsso.JsscComDriver;
import com.app.serial.jsso.SerialPortListener;
import jssc.SerialPort;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 *@author:
 *@program: app-admin
 *@name CheckSerialThread
 *@description: 监测串口的线程
 */
@Slf4j
@Component
@EnableScheduling
@EnableAsync
public class CheckSerialThread {

    /**
     *功能描述 每隔五秒查询一次串口状态
     * @author lizhi
     * @date 2021/12/21
     * @param
     * @return void
     */
    @Async
    @Scheduled(cron = "0/5 * * * * ?")
    public void checkSerial(){
        try {
            String portName = SerialConfig.getPortName();
            Integer baudRate = SerialConfig.getBaudRate();
            Map<String, SerialPort> serialPortMap = JsscComDriver.serialPortMap;
            if (serialPortMap.containsKey(portName)) {
                SerialPort serialPort = serialPortMap.get(portName);
                if (!serialPort.isOpened()) {
                    JsscComDriver.openSerialPort(portName, baudRate, SerialPortListener.class);
                    log.info("重新打开串口[{}],波特率是:{}成功", portName, baudRate);
                }
            } else {
                JsscComDriver.openSerialPort(portName, baudRate, SerialPortListener.class);
                log.info("打开串口[{}],波特率是:{}成功", portName, baudRate);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("串口出现异常退出");
        }
    }
}
